using System.Collections.Generic;
using System.Drawing;
using GTA;
using NativeUI;

namespace CustomPeds.Menus;

public class SettingMenu : Script
{
    public static UIMenu menu = new UIMenu("", TextSetting.cs_Menu, new Point(0, -107));

    private static UIMenuCheckboxItem CbxCanWearHelmetItem;
    private static UIMenuCheckboxItem CbxAutoAttackItem;
    private static UIMenuCheckboxItem CbxFollowItem;
    private static UIMenuCheckboxItem CbxInvincibleItem;
    private static UIMenuCheckboxItem CbxAvoidHazardsItem;
    private static UIMenuCheckboxItem CbxAutoExitOnReachItem;

    private static List<dynamic> DrivingStyleText = new List<object>(new string[6]
    {
        TextSetting.cs_ListItem_DS_SOT,
        TextSetting.cs_ListItem_DS_ATE,
        TextSetting.cs_ListItem_DS_AT,
        TextSetting.cs_ListItem_DS_N,
        TextSetting.cs_ListItem_DS_IL,
        TextSetting.cs_ListItem_DS_R
    });

    private static UIMenuListItem DrivingStyleItem;
    private static List<dynamic> HazardSensitivityText = new List<object>(new string[3]
    {
        TextSetting.cs_ListItem_Sensitivity_Low,
        TextSetting.cs_ListItem_Sensitivity_Medium,
        TextSetting.cs_ListItem_Sensitivity_High
    });
    private static UIMenuListItem HazardSensitivityItem;

    private static List<dynamic> seatList = new List<object>(new string[6]
    {
        TextSetting.cs_ListItem_CS_LF,
        TextSetting.cs_ListItem_CS_RF,
        TextSetting.cs_ListItem_CS_LR,
        TextSetting.cs_ListItem_CS_RR,
        TextSetting.cs_ListItem_CS_ES1,
        TextSetting.cs_ListItem_CS_ES2
    });

    private static UIMenuListItem ChangeSeatItem;

    private static Origin origin;

    private static bool inited;

    public SettingMenu()
    {
        if (!inited)
        {
            Main.pool.Add(menu);
            menu.OnMenuClose += OnMenuClose;
            menu.OnCheckboxChange += OnCheckboxChange;
            menu.OnListChange += OnListChange;
            inited = true;
        }
    }

    public static void InitCharacterSettingMenu(Main.Member member)
    {
        menu.Clear();
        menu.SetBannerType(new UIResRectangle());
        origin = (member == Main.Member.P2) ? Main.P2 : Main.P1;

        CbxCanWearHelmetItem = new UIMenuCheckboxItem(TextSetting.cs_CbxItem_CanWearHelmet, origin.CanWearHelmet);
        CbxAutoAttackItem = new UIMenuCheckboxItem(TextSetting.cs_CbxItem_AutoAttack, origin.AutoAttack);
        CbxFollowItem = new UIMenuCheckboxItem(TextSetting.cs_CbxItem_Follow, origin.Follow);
        CbxInvincibleItem = new UIMenuCheckboxItem(TextSetting.cs_CbxItem_Invincible, origin.Invincible);
        CbxAvoidHazardsItem = new UIMenuCheckboxItem(TextSetting.cs_CbxItem_AvoidHazards, origin.AvoidHazards);
        CbxAutoExitOnReachItem = new UIMenuCheckboxItem(TextSetting.cs_CbxItem_AutoExitOnReach, origin.AutoExitOnReach);

        DrivingStyleItem = new UIMenuListItem(TextSetting.cs_ListItem_DrivingStyle, DrivingStyleText, DrivingFlagsToIndex(origin.drivingFlags));
        HazardSensitivityItem = new UIMenuListItem(TextSetting.cs_ListItem_HazardSensitivity, HazardSensitivityText, origin.HazardSensitivityIndex);
        ChangeSeatItem = new UIMenuListItem(TextSetting.cs_ListItem_ChangeSeat, seatList, origin.SeatIndex + 1);

        if (member == Main.Member.P2)
        {
            menu.AddItem(CbxCanWearHelmetItem);
            menu.AddItem(CbxAutoAttackItem);
            menu.AddItem(CbxFollowItem);
            menu.AddItem(CbxInvincibleItem);
            menu.AddItem(CbxAvoidHazardsItem);
            menu.AddItem(CbxAutoExitOnReachItem);
            menu.AddItem(HazardSensitivityItem);
            menu.AddItem(DrivingStyleItem);
            menu.AddItem(ChangeSeatItem);
        }
        else
        {
            menu.AddItem(CbxCanWearHelmetItem);
            // 若需要也可开放给 P1：
            // menu.AddItem(CbxAvoidHazardsItem);
            // menu.AddItem(HazardSensitivityItem);
            // menu.AddItem(CbxAutoExitOnReachItem);
            menu.AddItem(DrivingStyleItem);
            menu.AddItem(ChangeSeatItem);
        }
        menu.RefreshIndex();
        menu.Visible = true;
    }

    private static void OnCheckboxChange(UIMenu sender, UIMenuCheckboxItem item, bool @checked)
    {
        if (item.Text == CbxCanWearHelmetItem.Text)
        {
            origin.CanWearHelmet = @checked;
            if (origin.Character != null && origin.Character.Exists())
            {
                origin.Character.CanWearHelmet = @checked;
                if (!@checked)
                {
                    origin.Character.RemoveHelmet(instantly: true);
                }
            }
        }
        if (item.Text == CbxAutoAttackItem.Text)
        {
            origin.AutoAttack = @checked;
        }
        if (item.Text == CbxFollowItem.Text)
        {
            origin.Follow = @checked;
            if (origin.Character != null && origin.Character.Exists())
            {
                if (@checked)
                {
                    origin.Character.Task.ClearAllImmediately();
                    Main.P1.Character.PedGroup.Add(origin.Character, leader: false);
                    origin.Character.PlayAmbientSpeech1("GENERIC_HI", immediately: true);
                }
                else
                {
                    origin.Character.PlayAmbientSpeech1("GENERIC_BYE", immediately: true);
                    origin.Character.IsSpeechPlayingToEnd();
                    origin.Character.LeaveGroup();
                    origin.Character.Task.ClearAllImmediately();
                }
            }
        }
        if (item.Text == CbxInvincibleItem.Text)
        {
            origin.Invincible = @checked;
            if (origin.Character != null && origin.Character.Exists())
            {
                origin.Character.IsInvincible = @checked;
            }
        }
        if (item.Text == CbxAvoidHazardsItem.Text)
        {
            origin.AvoidHazards = @checked;
        }
        if (item.Text == CbxAutoExitOnReachItem.Text)
        {
            origin.AutoExitOnReach = @checked;
        }
    }

    private static void OnListChange(UIMenu sender, UIMenuListItem list, int index)
    {
        if (list.Text == DrivingStyleItem.Text)
        {
            origin.drivingFlags = IndexToDrivingFlags(index);
            if (origin.Character != null && origin.Character.Exists())
            {
                origin.Character.VehicleDrivingFlags = origin.drivingFlags;
            }
        }
        if (list.Text == HazardSensitivityItem.Text)
        {
            origin.HazardSensitivityIndex = index;
        }
        if (origin.Character != null && origin.Character.IsInVehicle() && list.Text == ChangeSeatItem.Text)
        {
            origin.SeatIndex = MenuIndexToSeatId(index);
            origin.Character.Task.EnterVehicle(origin.Character.CurrentVehicle, (VehicleSeat)MenuIndexToSeatId(index), 3000, 2f, EnterVehicleFlags.WarpIn);
        }
    }

    private static int MenuIndexToSeatId(int index)
    {
        return index switch
        {
            0 => -1,
            1 => 0,
            2 => 1,
            3 => 2,
            4 => 3,
            5 => 4,
            _ => index,
        };
    }

    private static int DrivingFlagsToIndex(VehicleDrivingFlags flags)
    {
        switch (flags)
        {
            case VehicleDrivingFlags.DrivingModeStopForVehiclesStrict: return 0;
            case VehicleDrivingFlags.DrivingModeAvoidVehiclesReckless: return 1;
            case VehicleDrivingFlags.DrivingModeAvoidVehicles: return 2;
            case VehicleDrivingFlags.DrivingModeStopForVehicles: return 3;
            case VehicleDrivingFlags.DrivingModeStopForVehiclesIgnoreLights: return 4;
            case VehicleDrivingFlags.DrivingModePloughThrough: return 5;
            default: return 3;
        }
    }

    private static VehicleDrivingFlags IndexToDrivingFlags(int index)
    {
        // 使用 SHVDN3 实际存在的 DrivingMode 常量进行近似映射
        switch (index)
        {
            case 0: // Sometimes Overtake Traffic -> StopForVehiclesStrict (更保守)
                return VehicleDrivingFlags.DrivingModeStopForVehiclesStrict;
            case 1: // Avoid Traffic Extremely -> AvoidVehiclesReckless（更激进）
                return VehicleDrivingFlags.DrivingModeAvoidVehiclesReckless;
            case 2: // Avoid Traffic -> AvoidVehicles
                return VehicleDrivingFlags.DrivingModeAvoidVehicles;
            case 3: // Normal -> StopForVehicles（较为温和）
                return VehicleDrivingFlags.DrivingModeStopForVehicles;
            case 4: // Ignore Lights -> StopForVehiclesIgnoreLights
                return VehicleDrivingFlags.DrivingModeStopForVehiclesIgnoreLights;
            case 5: // Rushed -> PloughThrough（更激进）
                return VehicleDrivingFlags.DrivingModePloughThrough;
            default:
                return VehicleDrivingFlags.DrivingModeStopForVehicles;
        }
    }

    // 删除 DrivingStyle 相关映射，统一通过 VehicleDrivingFlags 控制

    private static void OnMenuClose(UIMenu sender)
    {
        // 最小化关闭逻辑：避免退格触发大量状态切换引发卡死/闪退
        try { LogHelper.WriteInfo("SettingMenu closed"); } catch { }
        menu.Visible = false;
        // 不刷新、不回写引用、不自动打开上级
    }
}


